<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏大厅</title>
    <link rel="icon" href="image/favicon.ico">
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_hall.css">
</head>
<body>
<div class="nav">五子棋对战</div>
<!-- 页面的容器元素 -->
<div class="container">
    <!-- 这个div 在 container 中位于垂直水平居中 -->
    <div>
        <!-- 用户信息 -->
        <div id="screen"></div>

        <!-- 匹配按钮 -->
        <div id="match-button" onclick="match()">开始匹配</div>
    </div>
</div>
<script src="js/jquery.min.js"></script>
    <script>
        $("#screen").val();
        $.ajax({
            type: "get",
            url: "/user/getUserInfo",
            success: function (result) {
                if (result == null || result.data == null || result.code == 401 || result.code == 400) {
                    alert("您当前未登录!");
                    location.replace("login.html");
                }
                console.log(result);
                console.log(result.data);
                let body = result.data;
                // 解析ISO时间字符串
                const updateTime = new Date(body.updateTime);
                // 格式化为常用时间格式：YYYY-MM-DD HH:mm:ss
                const formattedTime = updateTime.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                 }).replace(/\//g, '-');

                $("#screen").html('玩家: ' + body.userName + " 分数: " + '<span style="color:red ">'+body.score+'</span>'
                    + '<br> <span style="color: #f12fff;">比赛场次：' + body.totalCount + '</span>'
                    + '<span style="color: #FFD700;"> 获胜场数：' + body.winCount + '</span>'
                    +'<br> <span style="color: greenyellow;">势均力敌数：' + body.draw + '</span>'
                    + '<br> <span style="color: black;"> 最近游戏时间：' + formattedTime + '</span>');
            },
            error: function () {
                alert("您当前未登录!");
                location.replace("login.html");
            }
        });

        let matchButton = $("#match-button");
        // 获取 websocket 连接
        let websocket = new WebSocket('ws://'+location.host+'/match');
        websocket.onopen = function () {
            console.log("建立连接!");
        }

        websocket.onclose = function () {
            console.log("连接关闭!");
        }

        websocket.onerror = function () {
            console.log("连接异常关闭!");
        }

        window.onbeforeunload = function () {
            console.log("监测页面状态关闭/刷新")
            websocket.close();
        }

        // 监听页面隐藏事件（适用于现代浏览器）
        window.onpagehide = function () {
            console.log('页面隐藏，关闭 WebSocket 连接');
            websocket.close();
        }
        // 处理从后端传来的信息
        websocket.onmessage = function (event) {

            // 把服务器发送过来的 信息载荷 转化为 对象
            let result = JSON.parse(event.data);
            console.log(result);

            // 错误信息
            if (result == null || result.code == 400) {
                alert(result.message);
                location.replace("login.html");
                return;
            }
            // 未登录
            if (result.code == 401) {
                alert(result.message);
                location.replace("login.html");
                return;
            }
            // 开始匹配
            if (result != null && result.code == 200 && result.message == 'startMatch') {
                console.log("开始匹配");
                console.log(result.message);
                matchButton.html("正在匹配中(点击取消)");
            }else if (result != null && result.code == 200 && result.message == 'stopMatch') {
                console.log("停止匹配");
                console.log(result.message);
                matchButton.html("开始匹配");
            }else if (result != null && result.code == 200 && result.message == 'success') {
                console.log(result.message);
                location.replace("game_room.html");
            }else {
                alert(result.message);
                location.replace("login.html");
            }
        }

        function match() {
            console.log(websocket.readyState);
            // 检查连接是否正常
            if (websocket.readyState == websocket.OPEN) {
                if (matchButton.html() == "开始匹配") {
                    websocket.send(JSON.stringify({
                        message: "startMatch"
                    }));
                }else if (matchButton.html() == "正在匹配中(点击取消)") {
                    websocket.send(JSON.stringify({
                        message: "stopMatch"
                    }));
                }else {
                    alert("错误显示");
                    location.replace("login.html");
                }
            }else {
                alert("您可能未登录, 连接断开, 请重新登录!");
                location.replace("login.html");
            }
        }


    </script>
</body>
</html>